﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DataBaseLibrary.DBObjectsFB;
using DataBaseLibrary.DBInterfaces;
using Application = DataBaseLibrary.DBObjectsFB.Application;


namespace DocMreoLiteVersion.Reports.DeclarationReport
{

    /// <summary>
    /// Interaction logic for FormDeclarationReport.xaml
    /// </summary>
    public partial class FormDeclarationReport : UserControl
    {


        /// <summary>
        /// Событие закрытия формы
        /// </summary>
        delegate void CloseFormDeclarationEventHandler(object sender, RoutedEventArgs args);
        public static readonly RoutedEvent CloseFormDeclarationEvent = EventManager.RegisterRoutedEvent("CloseFormDeclaration", RoutingStrategy.Bubble, typeof(CloseFormDeclarationEventHandler), typeof(FormDeclarationReport));

        public event RoutedEventHandler CloseFormDeclaration
        {
            add { AddHandler(CloseFormDeclarationEvent, value); }
            remove { RemoveHandler(CloseFormDeclarationEvent, value); }
        }

        public static DependencyProperty IdRecordProperty = DependencyProperty.Register("ID_RECORD", typeof(String), typeof(FormDeclarationReport));
        
        //ID полученной записи!
        public String ID_RECORD
        {
            set { SetValue(IdRecordProperty, value); }
            get { return (String)GetValue(IdRecordProperty); }
        }



        IDBObject _mDeclarationContract;

        /// <summary>
        /// Провайдер базы данных
        /// </summary>
        private readonly IDBProvider _dbProvider = null;

        /// <summary>
        /// Конструктор
        /// </summary>
        public FormDeclarationReport()
        {
            _mDeclarationContract = new DataBaseLibrary.DBObjectsFB.Application();
            InitializeComponent();
            
        }

        /// <summary>
        /// Конструктор загрузки по номеру заявления
        /// </summary>
        /// <param name="mProvider">Провайдер БД</param>
        /// <param name="idRecord">Номер заявления</param>
        public FormDeclarationReport(IDBProvider mProvider, String idRecord = "")
            : this()
        {
            _dbProvider = mProvider;

            if (_dbProvider == null)
            {
                MessageBox.Show("Нет провайдера БД");
                return;
            }


            _mDeclarationContract = new DataBaseLibrary.DBObjectsFB.Application();
            LoadContract(idRecord);            
            this.DataContext = _mDeclarationContract;
            
            DeclarantControl.IndividualObject = (_mDeclarationContract as Application).Owner;
            RepresentativeDeclarantControl.IndividualObject = (_mDeclarationContract as Application).Representative.OIndividual;
            TransportControl.VechicleObject = (_mDeclarationContract as Application).Vehicle;
            RepresentativeProxyInfoControl.RepresentativeObject = (_mDeclarationContract as Application).Representative;

            DeclarantControl.Provider = _dbProvider;
            RepresentativeDeclarantControl.Provider = _dbProvider;


        }

        /// <summary>
        /// Создания нового заявления по имеющимся данным
        /// </summary>
        /// <param name="mProvider">Провайдер БД</param>
        /// <param name="loadOwner">Объект заявителя</param>
        /// <param name="loadRepresentative">Объект представителя</param>
        /// <param name="loadVechicle">Объект ТС</param>

        public FormDeclarationReport(IDBProvider mProvider, Individual loadOwner, Representative loadRepresentative, Vechicle loadVechicle)
            :this()
        {
            _dbProvider = mProvider;
            if (_dbProvider == null)
            {
                MessageBox.Show("Нет провайдера БД");
                return;
            }

            _mDeclarationContract = new DataBaseLibrary.DBObjectsFB.Application();
            if (loadOwner != null)
                (_mDeclarationContract as Application).Owner = loadOwner;
            if (loadRepresentative != null)
                (_mDeclarationContract as Application).Representative = loadRepresentative;
                
            if (loadVechicle != null)
                (_mDeclarationContract as Application).Vehicle = loadVechicle;

            this.DataContext = _mDeclarationContract;


            DeclarantControl.IndividualObject = (_mDeclarationContract as Application).Owner;
            RepresentativeDeclarantControl.IndividualObject = (_mDeclarationContract as Application).Representative.OIndividual;
            TransportControl.VechicleObject = (_mDeclarationContract as Application).Vehicle;
            RepresentativeProxyInfoControl.RepresentativeObject = (_mDeclarationContract as Application).Representative;

        }



        /// <summary>
        /// Загрузка заявления по ID
        /// </summary>
        /// <param name="idRecord"></param>
        private void LoadContract(String idRecord)
        {
            if (idRecord == ID_RECORD)
            {
                MessageBox.Show(String.Format("Заявление {0} уже загружено!", ID_RECORD));
                return;
            }

            if (idRecord == String.Empty)
                return;

            try
            {
                _dbProvider.Load(_mDeclarationContract, idRecord);
                ID_RECORD = idRecord;
            }
            catch(SystemException err)
            {                
                MessageBox.Show(err.Message, "Ошибка ввода", MessageBoxButton.OK, MessageBoxImage.Error);
                MessageBox.Show("Будет создано новое заявление!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
                ID_RECORD = "";
                _mDeclarationContract = new DataBaseLibrary.DBObjectsFB.Application();

            }
        }

        /// <summary>
        /// Сохранение данных в БД и печать заявления
        /// </summary>
        private void SaveUpdateContract()
        {
            if (_dbProvider == null)
                return;

            try
            {
                if (string.IsNullOrEmpty(ID_RECORD))
                {
                    ID_RECORD = _dbProvider.Save(_mDeclarationContract) as String;
                    IDBLogic logic = new FDBLogic(_dbProvider);
                    logic.AddDocumentHistory(MainWindow.session.user, ID_RECORD, _mDeclarationContract.ToString(),
                        "Создание", DateTime.Now, 180.00);
                }
                else
                {
                    _dbProvider.Update(_mDeclarationContract);
                    IDBLogic logic = new FDBLogic(_dbProvider);
                    logic.AddDocumentHistory(MainWindow.session.user, ID_RECORD, _mDeclarationContract.ToString(), "Обновление", DateTime.Now, 180.00);
                }


                var mDataDeclarationReportBinding = new DataDeclarationReportBinding(
                                                              _mDeclarationContract as
                                                              DataBaseLibrary.DBObjectsFB.Application);
                var rWindow = new ReportViewverWindow("DocMreoLiteVersion.Reports.DeclarationReport.DeclarationReport_p1.rdlc", "DeclarationContractDataSet", mDataDeclarationReportBinding)
                    {
                        Owner = System.Windows.Application.Current.MainWindow
                    };

                rWindow.ShowDialog();
                rWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;

                rWindow = new ReportViewverWindow("DocMreoLiteVersion.Reports.DeclarationReport.DeclarationReport_p3.rdlc", "DeclarationContractDataSet", mDataDeclarationReportBinding)
                    {
                        Owner = System.Windows.Application.Current.MainWindow
                    };

                rWindow.ShowDialog();
                rWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                
            }
            catch (SystemException err)
            {
                MessageBox.Show(String.Format("Ошибка с сообщением: {0} \n {1}", err.Message, err.StackTrace));
            }
        }


        /// <summary>
        /// Завершить рабботу
        /// </summary>
        private void CloseContractForm()
        {
            RoutedEventCreateDeclarationArgs args = new RoutedEventCreateDeclarationArgs(CloseFormDeclarationEvent);
            if (ID_RECORD != null & ID_RECORD != String.Empty)
                args.ObjectContract = _mDeclarationContract;
            else
                args.ObjectContract = null;
            RaiseEvent(args);
        }



        /// <summary>
        /// обытия от органов управления
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void RecButton_Click_1(object sender, RoutedEventArgs e)
        {
            SaveUpdateContract();
        }

        private void CancelButton_Click_1(object sender, RoutedEventArgs e)
        {
            CloseContractForm();
        }

    }
}
